<template>
  <div class="app-container">

    <!-- 左右布局：左侧用户列表，右侧用户详情 -->
    <el-row :gutter="10">
      <!-- 左侧用户列表 -->
      <el-col :span="8">
        <div class="user-list-container">
          <!-- 简化的搜索区域 -->
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px" class="search-form">
            <el-form-item label="" prop="tel">
              <el-input
                prefix-icon="el-icon-search"
                v-model="queryParams.params.searchText"
                placeholder="姓名/手机号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 用户列表 -->
          <el-table
            v-loading="loading"
            :data="miniappUserList"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            highlight-current-row
            class="user-table"
            stripe
            border
          >
            <el-table-column fixed label="ID" align="center" prop="id" width="50"/>
            <el-table-column label="昵称" align="center" prop="nickName" />
            <el-table-column label="性别" align="center" prop="sex" width="50">
              <template slot-scope="scope">
                {{scope.row.sex == null ? '未知' : (scope.row.sex == 1 ? '女' : '男')}}
              </template>
            </el-table-column>
            <el-table-column label="电话" align="center" prop="tel" />
            <el-table-column label="操作" align="center" width="65">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click.stop="handleUpdate(scope.row)"
                  v-hasPermi="['basics:appUser:edit']"
                >修改</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            layout="total, prev, next, jumper"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-col>

      <!-- 右侧用户详情 -->
      <el-col :span="16">
        <div class="user-detail-container">
          <!-- 用户未选择时的提示 -->
          <el-empty v-if="!selectedUser" :image-size="200" class="empty-container"></el-empty>
          <!-- 用户详情内容 -->
          <div v-else>
            <!-- 用户档案信息 -->
            <el-card shadow="hover" class="user-profile-card">
              <div class="user-profile">
                <div class="user-profile-header">
                  <div class="user-avatar-large">
                    <img :src="userAvatar" alt="用户头像">
                  </div>
                  <div class="user-basic-info">
                    <h2>{{ selectedUser.nickName }}</h2>
                    <p>
                      <svg-icon icon-class="birthday"  class-name='custom-class' />{{ selectedUser.birthday || '未设置' }}
                      <span class="info-divider">|</span>
                      <svg-icon v-if="selectedUser.sex==0" icon-class="sex-male"  class-name='custom-class' />
                      <svg-icon v-else="selectedUser.sex==1" icon-class="sex-female"  class-name='custom-class' />
                      {{ selectedUser.sex == null ? '未知' : (selectedUser.sex == 1 ? '女' : '男') }}
                      <span class="info-divider">|</span>
                      {{ selectedUser.age ||'--' }}岁
                    </p>
                  </div>
                </div>
                <el-descriptions class="margin-top" :column="3" border>sex-female.svg
                  sex-male.svg
                  <el-descriptions-item>
                    <template slot="label">
                      <svg-icon icon-class="height"  class-name='custom-class' />
                      身高
                    </template>
                   {{ selectedUser.height || '--' }}cm
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <svg-icon icon-class="weight"  class-name='custom-class' />
                      体重
                    </template>
                    {{ selectedUser.weight || '--' }}kg
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <svg-icon icon-class="bmi"  class-name='custom-class' />
                      BMI
                    </template>
                    <span v-if="selectedUser.height && selectedUser.weight">
                      {{ calculateBMI(selectedUser.weight, selectedUser.height) }}
                      <el-tag
                        size="mini"
                        :type="getBMITagType(calculateBMI(selectedUser.weight, selectedUser.height))"
                        style="margin-left: 5px"
                      >
                        {{ getBMICategory(calculateBMI(selectedUser.weight, selectedUser.height)) }}
                      </el-tag>
                    </span>
                    <span v-else>--</span>
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-mobile-phone"></i>
                      手机号
                    </template>
                    {{ selectedUser.tel || '--' }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <svg-icon icon-class="xcx"  class-name='custom-class' />
                      归属小程序
                    </template>
                    {{ selectedUser.miniAppName || '未知' }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-tickets"></i>
                      备注
                    </template>
                    {{ selectedUser.remark }}
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-timer"></i>
                      注册时间
                    </template>
                    <el-tag size="small">{{ formatDate(selectedUser.createTime) }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item>
                    <template slot="label">
                      <i class="el-icon-office-building"></i>
                      联系地址
                    </template>
                    {{ selectedUser.address || '--' }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </el-card>

            <!-- 选项卡导航 -->
            <el-tabs v-model="activeTab" class="user-detail-tabs" @tab-click="handleTabClick">
              <el-tab-pane label="体重监测" name="weight">
                <!-- 体重统计卡片 -->
                <el-row :gutter="20" class="weight-stats-cards">
                  <el-col :span="6">
                    <el-card shadow="hover" class="stats-card">
                      <div class="stats-card-content">
                        <div class="stats-card-value">{{ weightStats.recordCount || 0 }}</div>
                        <div class="stats-card-label">历史打卡次数</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :span="6">
                    <el-card shadow="hover" class="stats-card">
                      <div class="stats-card-content">
                        <div class="stats-card-value">{{ weightStats.avgWeight || '0.0' }}</div>
                        <div class="stats-card-label">平均体重 (kg)</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :span="6">
                    <el-card shadow="hover" class="stats-card">
                      <div class="stats-card-content">
                        <div class="stats-card-value">{{ weightStats.maxWeight || '0.0' }}</div>
                        <div class="stats-card-label">最大体重 (kg)</div>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col :span="6">
                    <el-card shadow="hover" class="stats-card">
                      <div class="stats-card-content">
                        <div class="stats-card-value">{{ weightStats.minWeight || '0.0' }}</div>
                        <div class="stats-card-label">最小体重 (kg)</div>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>

                <!-- 体重记录展示区域 -->
                <el-row :gutter="20" class="weight-display-area">
                  <!-- 左侧日历展示 -->
                  <el-col :span="12">
                    <el-card shadow="hover" class="calendar-card">
                      <div slot="header" class="clearfix">
                        <span>体重打卡日历</span>
                      </div>
                      <el-calendar v-model="calendarDate" @change="handleCalendarChange">
                        <template slot="dateCell" slot-scope="{date, data}">
                          <div class="calendar-day calendar-day-content">
                            <div>{{ data.day.split('-').slice(2).join('-') }}</div>
                            <div v-if="hasWeightRecord(date)" class="calendar-data-primary">
                              {{ getWeightForDate(date) }} kg
                            </div>
                            <div v-else="hasWeightRecord(date)" class="calendar-data-danger">
                              未打卡
                            </div>
                          </div>
                        </template>
                      </el-calendar>
                    </el-card>
                  </el-col>

                  <!-- 打卡历史数据 -->
                  <el-col :span="12">
                    <el-card shadow="hover" class="weight-history-table">
                      <div slot="header" class="clearfix">
                        <span>体重历史记录</span>
                      </div>
                      <el-table :data="weightHistoryList" style="width: 100%;" v-if="weightHistoryList.length > 0" border stripe>
                        <el-table-column label="记录日期" prop="date" align="center">
                          <template slot-scope="scope">
                            {{ scope.row.date.split(' ')[0] }}
                          </template>
                        </el-table-column>
                        <el-table-column label="体重(kg)" prop="weight" align="center" />
                        <el-table-column label="BMI" align="center">
                          <template slot-scope="scope">
                            <span>{{ calculateBMI(scope.row.weight, selectedUser.height) }}</span>
                            <el-tag
                              size="mini"
                              :type="getBMITagType(calculateBMI(scope.row.weight, selectedUser.height))"
                              style="margin-left: 5px"
                            >
                              {{ getBMICategory(calculateBMI(scope.row.weight, selectedUser.height)) }}
                            </el-tag>
                          </template>
                        </el-table-column>
                      </el-table>
                      <div v-else class="empty-data-placeholder">
                        <i class="el-icon-s-data"></i>
                        <p>暂无体重记录</p>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>

                <!-- 体重历史记录表格 -->
                <el-card shadow="hover" class="chart-card">
                  <div slot="header" class="clearfix">
                    <span>最近15天体重变化</span>
                  </div>
                  <div v-if="weightHistoryList.length === 0" class="empty-chart-placeholder">
                    <i class="el-icon-data-line"></i>
                    <p>暂无体重记录数据</p>
                  </div>
                  <div v-else id="weightChart" class="weight-chart"></div>
                </el-card>
              </el-tab-pane>


              <!-- 运动监测 -->
              <el-tab-pane label="运动监测" name="exercise">
                <div class="tab-content-placeholder">
                    <Calendar @dateValue="handleCalendarChoice"></Calendar>
                    <SportHistory ref="sportHistory" :queryDate="calendarDate" :userId="selectedUser.id" :openId="selectedUser.openId"></SportHistory>
                </div>


              </el-tab-pane>

              <!-- 饮食监测 -->
              <el-tab-pane label="饮食监测" name="diet">
                <div class="tab-content-placeholder">
                  <i class="el-icon-data-line"></i>
                  <p>饮食监测功能开发中...</p>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改小程序用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="照片" prop="avatar">
          <el-avatar size="large" :src="form.avatar"></el-avatar>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="openID" prop="openId">
              <el-input disabled v-model="form.openId" placeholder="请输入openId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属小程序" prop="miniAppName">
              <el-select disabled v-model="form.miniAppId" placeholder="请选择">
                <el-option
                  v-for="item in miniAppList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input disabled v-model="form.nickName" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身高cm" prop="height">
              <el-input-number v-model="form.height"  :step="10" controls-position="right" :max="250"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重kg" prop="weight">
              <el-input-number v-model="form.weight" :precision="2" controls-position="right" :step="5" :max="350"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入联系地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMiniappUser, updateMiniappUser,innerJoinList } from "@/api/miniapp/wxAappUser";
import { listSelect } from "@/api/miniapp/wxApp";
import { listHistoryData,historyAnalysis,listByHistory } from "@/api/miniapp/wxUserHistory";
import * as echarts from 'echarts';
import Calendar from "@/components/Calendar";
import SportHistory from "./sportHistory.vue";
export default {
  name: "MiniAppUser",
  dicts: ['sys_user_sex'],
  components:{
    Calendar,
    SportHistory
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小程序用户表格数据
      miniappUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        tel: null,
        miniAppId: null,
        params:{
          searchText:null,
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        realName: [
          { required: true, message: "用户姓名不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        tel: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "change" }]
      },
      miniAppList:[],
      // 当前选中的用户
      selectedUser: null,
      // 用户档案信息
      userProfile: {
        age: null,
        height: null,
        weight: null,
        bmi: null
      },
      // 体重历史数据
      weightHistoryList: [],
      // 体重日历数据
      calendarWeightData:[],
      // 体重记录对话框是否可见
      weightDialogVisible: false,
      // 体重记录表单
      weightForm: {
        id: null,
        userId: null,
        weight: null,
        recordDate: null,
        remark: null
      },
      // 体重记录表单验证规则
      weightRules: {
        weight: [
          { required: true, message: "体重不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入有效的体重数值", trigger: "blur" }
        ],
        recordDate: [
          { required: true, message: "记录日期不能为空", trigger: "change" }
        ]
      },
      // 体重统计数据
      weightStats: {
        recordCount: 0,
        avgWeight: '0.0',
        maxWeight: '0.0',
        minWeight: '0.0'
      },
      // 日历当前日期
      calendarDate: new Date(),
      // 当前选中的选项卡
      activeTab: 'weight',
      // 体重图表实例
      weightChart: null,
    };
  },
  created() {
    this.handleListSelect();
    this.getList();
  },
  mounted() {
    // 监听窗口大小变化，重新调整图表大小
    window.addEventListener('resize', this.resizeChart);
  },
  computed: {
    userAvatar() {
      if(this.selectedUser.sex==='1'){
        return this.selectedUser.avatar || require('@/assets/images/female.png');
      }else if(this.selectedUser.sex==='0'){
        return this.selectedUser.avatar || require('@/assets/images/male.png');
      }else{
        return this.selectedUser.avatar || require('@/assets/images/default.png');
      }
    }
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.resizeChart);
    // 销毁图表实例
    if (this.weightChart) {
      this.weightChart.dispose();
      this.weightChart = null;
    }
  },
  methods: {
    handleTabClick(tab) {
      // 当切换到目标 tab 时执行函数
      if (tab.name === 'exercise') {
        // 确保组件已加载
        this.$nextTick(() => {
          // 链式获取：父组件的$refs → 子组件 → 子组件的$refs → 孙子组件 → 调用函数
            const child = this.$refs.sportHistory;
            if (child && child.$refs.tabItems) {
              child.$refs.tabItems.calculateItemDimensions();
            }
        });
      }
    },
    handleCalendarChoice(date){
      this.calendarDate = new Date(date);
    },
    /** 初始化体重图表 */
    initWeightChart() {
      if (!this.weightHistoryList.length) return;

      // 如果已存在图表实例，先销毁
      if (this.weightChart) {
        this.weightChart.dispose();
      }

      // 获取DOM元素
      const chartDom = document.getElementById('weightChart');
      if (!chartDom) return;

      // 创建图表实例
      this.weightChart = echarts.init(chartDom);

      // 准备数据
      const dates = this.weightHistoryList.map(item => item.date);
      const weights = this.weightHistoryList.map(item => item.weight);

      // 配置项
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>体重: {c} kg'
        },
        grid: {
          left: '3%',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        xAxis: {
          name: '日期',
          type: 'category',
          data: dates,
          boundaryGap: false,
        },
        yAxis: {
          type: 'value',
          name: '体重(kg)',
          axisLabel: {
            formatter: '{value} kg'
          }
        },
        series: [{
          name: '体重',
          type: 'line',
          data: weights,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#409EFF'
          },
          lineStyle: {
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'rgba(64,158,255,0.3)'
            }, {
              offset: 1,
              color: 'rgba(64,158,255,0.1)'
            }])
          }
        }]
      };

      // 设置配置项
      this.weightChart.setOption(option);
    },

    /** 调整图表大小 */
    resizeChart() {
      if (this.weightChart) {
        this.weightChart.resize();
      }
    },
    /** 检查日期是否有体重记录 */
    hasWeightRecord(date) {
      const dateStr = this.formatDate(date);
      return this.calendarWeightData.some(record => record.date === dateStr);
    },

    /** 获取指定日期的体重记录 */
    getWeightForDate(date) {
      const dateStr = this.formatDate(date);
      const record = this.calendarWeightData.find(record => record.date === dateStr);
      return record ? record.weight : null;
    },

    /** 格式化日期 */
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    /** 查询小程序用户列表 */
    getList() {
      this.loading = true;
      innerJoinList(this.queryParams).then(response => {
        this.miniappUserList = response.rows;
        this.total = response.total;
        this.loading = false;

        // 如果有选中的用户，重新获取该用户的信息
        if (this.selectedUser) {
          const updatedUser = this.miniappUserList.find(user => user.id === this.selectedUser.id);
          if (updatedUser) {
            this.selectedUser = updatedUser;
            this.getWeightHistory(updatedUser);
          }
        }
      });
    },

    /** 处理用户行点击事件 */
    handleRowClick(row) {
      this.selectedUser = row;
      this.getWeightHistory(row);
    },

    /** 获取用户体重历史 */
    getWeightHistory(row) {
      // 获取日历当前年月
      const currentDate = this.calendarDate || new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;

      const params = {
        userId: row.id,
        openId: row.openId,
        miniAppId: row.miniAppId,
        year: year,
        month: month
      };
      // 用户历史打卡记录
      listHistoryData(params).then(response => {
        if (response && response.data) {
          this.weightHistoryList = response.data || [];
          // 初始化体重图表
          this.$nextTick(() => {
            this.initWeightChart();
          });
        }
      })
      // 获取用户统计分析数据
      historyAnalysis(params).then(response => {
        if (!response || !response.data || typeof response.data !== 'object') {
          this.weightStats = {
            recordCount: 0,
            avgWeight: '0.0',
            maxWeight: '0.0',
            minWeight: '0.0'
          };
          return;
        }
        this.weightStats = {
          recordCount: response.data.recordCount || 0,
          avgWeight: (response.data.avgWeight || 0).toFixed(1),
          maxWeight: (response.data.maxWeight || 0).toFixed(1),
          minWeight: (response.data.minWeight || 0).toFixed(1)
        };
      });
      // 按月获取用户体重记录 - 这是用于日历组件数据展示的
      listByHistory(params).then(response => {
        if (response && response.data) {
          // 保存日历数据
          this.calendarWeightData = response.data;
        }
      });
    },

    /** 监听日历月份变化 */
    handleCalendarChange(e) {
      if (this.selectedUser) {
        this.getWeightHistory(this.selectedUser);
      }
    },

    /** 计算BMI */
    calculateBMI(weight, height) {
      // 确保输入有效
      if (!weight || !height || weight <= 0 || height <= 0) {
        return '0.0';
      }
      // 确保身高单位是米
      const heightInMeters = height >= 3 ? height / 100 : height;
      // 计算BMI: 体重(kg) / 身高(m)²
      const bmi = weight / (heightInMeters * heightInMeters);
      // 返回保留一位小数的BMI值
      return bmi.toFixed(1);
    },
    /** 获取BMI分类 */
    getBMICategory(bmi) {
      if (!bmi || bmi <= 0) return '未知';
      const numBMI = parseFloat(bmi);
      if (numBMI < 18.5) return '偏瘦';
      if (numBMI < 24) return '正常';
      if (numBMI < 28) return '超重';
      return '肥胖';
    },
    /** 获取BMI标签类型 */
    getBMITagType(bmi) {
      if (!bmi || bmi <= 0) return 'info';
      const numBMI = parseFloat(bmi);
      if (numBMI < 18.5) return 'warning';  // 偏瘦
      if (numBMI < 24) return 'success';    // 正常
      if (numBMI < 28) return 'warning';    // 超重
      return 'danger';                      // 肥胖
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nickName: null,
        avatar: null,
        openId: null,
        weight: null,
        height: null,
        age: null,
        birthday: null,
        sex: null,
        miniAppId: null,
        remark: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /**  查询下拉框 */
    handleListSelect(){
      listSelect().then(res=>{
        this.miniAppList = res.data;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        tel: null,
        miniAppId: null,
        params:{
          searchText:null,
        }
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMiniappUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "用户信息维护";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            //如果出生日期不为空，计算年龄
            if (this.form.birthday) {
              const birthDate = new Date(this.form.birthday);
              this.form.age = this.calculateAge(birthDate);
            }
            updateMiniappUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    calculateAge(birthDate) {
        const today = new Date();
        const birthYear = birthDate.getFullYear();
        const currentYear = today.getFullYear();

        // 初步计算年龄
        let age = currentYear - birthYear;

        // 检查生日是否已过
        const birthMonth = birthDate.getMonth();
        const currentMonth = today.getMonth();

        if (currentMonth < birthMonth) {
          // 当前月份小于出生月份，生日未到
          age--;
        } else if (currentMonth === birthMonth) {
          // 月份相同，比较日期
          const birthDay = birthDate.getDate();
          const currentDay = today.getDate();
          if (currentDay < birthDay) {
            // 当前日期小于出生日期，生日未到
            age--;
          }
        }
        return age;
      }
  }
};
</script>

<style scoped>


.app-container {
  padding: 10px;
}

.user-list-container {
  background: #fff;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.user-detail-container {
  height: 100%;
}

.empty-container{
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 105px);
  border: 1px solid #e6ebf5;
  border-radius: 5px;
}
.empty-data-placeholder {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.empty-data-placeholder p {
  margin-top: 10px;
  font-size: 14px;
}

.empty-chart-placeholder {
  text-align: center;
  padding: 60px 0;
  color: #909399;
}

.empty-chart-placeholder i {
  font-size: 48px;
}

.empty-chart-placeholder p {
  margin-top: 10px;
  font-size: 14px;
}

/* 用户档案卡片样式 */
.user-profile-card {
  margin-bottom: 10px;
}

.user-profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.user-avatar-large {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20px;
  border: 2px solid #ebeef5;
}

.user-avatar-large img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-basic-info h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 600;
}

.user-basic-info p {
  margin: 0;
  color: #606266;
}

.info-divider {
  margin: 0 10px;
  color: #dcdfe6;
}


/* 选项卡样式 */
.user-detail-tabs {
  padding: 15px;
  margin-top: 10px;
  border-radius: 5px;
  border: 1px solid #e6ebf5;
}

 .user-detail-tabs:hover {
   box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
 }

.tab-content-placeholder {
  text-align: center;

  color: #909399;
}

.tab-content-placeholder i {
  font-size: 48px;
}

.tab-content-placeholder p {
  margin-top: 10px;
  font-size: 14px;
}

/* 体重统计卡片样式 */
.weight-stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: auto;
}

.stats-card-content {
  text-align: center;
  padding: 10px 0;
}

.stats-card-value {
  font-size: 24px;
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 5px;
}

.stats-card-label {
  font-size: 12px;
  color: #909399;
}

/* 体重展示区域样式 */
.weight-display-area {
  margin-bottom: 20px;
}

.calendar-card, .chart-card {
  height: 400px;
  overflow: hidden;
}

.calendar-day {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 2px;
}

.calendar-day-content {
  text-align: center;

  .calendar-data-danger {
    padding: 4px 2px;
    border-radius: 4px;
    font-size: 10px;
    margin-top: 2px;
    color: white;
    background-color: rgb(245, 108, 108,0.5);
  }
  .calendar-data-primary {
    padding: 4px 2px;
    border-radius: 4px;
    font-size: 10px;
    margin-top: 2px;
    color: white;
    background-color: rgb(102, 177, 255);
  }
}

.weight-chart {
  height: 340px;
}

/* 体重历史表格样式 */
.weight-history-table {
  height: auto;
}

.calendar-day{
  text-align: center;
}


::v-deep {
   .el-calendar-day {
    padding: 5px !important;
    height: auto !important;
  }

   .el-card__body {
    padding: 10px !important;
  }
   .el-calendar__body {
    padding: 0;
  }
   .calendar-card {
    height: auto !important;
    overflow: hidden;
  }

   .el-calendar-table:not(.is-range) td.prev,
   .el-calendar-table:not(.is-range) td.next {
    cursor: not-allowed;
    pointer-events: none;
  }
  /* 完全隐藏其他月份的日期 */


  .prev > .el-calendar-day,
  .next > .el-calendar-day {
    display: none !important;
  }

  /* 完全隐藏其他月份的日期 */
  .prev,
  .next {

  }

  /* 确保当前月份的日期正常显示 */
  .current {
    visibility: visible !important;
    height: auto !important;
  }

  /* 确保当前月份的日期正常显示 */
  .current > .el-calendar-day {
    height: auto !important;
    padding: 5px !important;
  }

}
</style>
